/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gra.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gra.dao.QuestionDao;
import com.thinkgem.jeesite.modules.gra.entity.Paper;
import com.thinkgem.jeesite.modules.gra.entity.Question;
import com.thinkgem.jeesite.modules.gra.entity.Score;
import com.thinkgem.jeesite.modules.gra.service.PaperService;
import com.thinkgem.jeesite.modules.gra.service.ScoreService;

/**
 * 试卷管理Controller
 * @author wuzengli
 * @version 2017-05-04
 */
@Controller
@RequestMapping(value = "${adminPath}/gra/paper")
public class PaperController extends BaseController {

	@Autowired
	private PaperService paperService;
	@Autowired
	private ScoreService scoreService;
	@Autowired
	private QuestionDao questionDao;
	private String paperId;
	private List<Question> squestionList=new ArrayList<Question>();
	private List<Question> mquestionList=new ArrayList<Question>();
	private Score score = new Score();
	
	
	public String getPaperId() {
		return paperId;
	}

	public void setPaperId(String paperId) {
		this.paperId = paperId;
	}
	
	public List<Question> getSquestionList() {
		return squestionList;
	}

	public void setSquestionList(List<Question> squestionList) {
		this.squestionList = squestionList;
	}

	public List<Question> getMquestionList() {
		return mquestionList;
	}

	public void setMquestionList(List<Question> mquestionList) {
		this.mquestionList = mquestionList;
	}

	public Score getScore() {
		return score;
	}

	public void setScore(Score score) {
		this.score = score;
	}

	@ModelAttribute
	public Paper get(@RequestParam(required=false) String id) {
		Paper entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = paperService.get(id);
		}
		if (entity == null){
			entity = new Paper();
		}
		return entity;
	}
	
	@RequiresPermissions("gra:paper:view")
	@RequestMapping(value = {"list", ""})
	public String list(Paper paper, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Paper> page = paperService.findPage(new Page<Paper>(request, response), paper); 
		model.addAttribute("page", page);
		return "modules/gra/paperList";
	}

	@RequiresPermissions("gra:paper:view")
	@RequestMapping(value = "form")
	public String form(Paper paper, Model model) {
		model.addAttribute("paper", paper);
		return "modules/gra/paperForm";
	}

	@RequiresPermissions("gra:paper:edit")
	@RequestMapping(value = "save")
	public String save(Paper paper, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, paper)){
			return form(paper, model);
		}
		paperService.save(paper);
		addMessage(redirectAttributes, "保存试卷管理成功");
		return "redirect:"+Global.getAdminPath()+"/gra/paper/?repage";
	}
	
	@RequiresPermissions("gra:paper:edit")
	@RequestMapping(value = "delete")
	public String delete(Paper paper, RedirectAttributes redirectAttributes) {
		paperService.delete(paper);
		addMessage(redirectAttributes, "删除试卷管理成功");
		return "redirect:"+Global.getAdminPath()+"/gra/paper/?repage";
	}
	
	@RequestMapping(value = {"exam"})
	public String exam(Paper paper, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Paper> page = paperService.findPage(new Page<Paper>(request, response),paper); 
		model.addAttribute("page", page);
		return "modules/gra/examChoose";
	}
	
	@RequestMapping(value = {"examLine"})
	public String examLine(Paper paper,HttpServletRequest request, HttpServletResponse response, Model model) {
		Paper paperLine=paperService.get(paper.getId());
		List<Question> questionList=paperLine.getQuestionList();
		Iterator<Question> it=questionList.iterator();
		while(it.hasNext()){
			Question q=it.next();
			if("1".equals(q.getType())){
				squestionList.add(q);
			}else{
				mquestionList.add(q);
			}
		}
		squestionList=this.getRandowQuestion(squestionList, 3);
		mquestionList=this.getRandowQuestion(mquestionList, 2);
		model.addAttribute("paperId",paper.getId());
		model.addAttribute("squestionList", squestionList);
		model.addAttribute("mquestionList", mquestionList);
		return "modules/gra/examLine";
	}
	
	private List<Question> getRandowQuestion(List<Question> questionList,int num){
		List<Question> resultList=new ArrayList<Question>();
		Random random=new Random();
		if(num>0){
			for(int i=1;i<=num;i++){
				int n=random.nextInt(questionList.size());
				Question q=questionList.get(n);
				if(resultList.contains(q)){
					i--;
				}else{
					resultList.add(q);
				}
			}
		}
		return resultList;
	}
	
	@RequestMapping(value = {"examResult"})
	public String examResult(Paper paper, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		@SuppressWarnings("unchecked")
		Map<String, String[]> keyMap=request.getParameterMap();
		Iterator<Entry<String, String[]>> it2=keyMap.entrySet().iterator();
		int totalScore=0;
		int singleScore=0;
		int moreScore=0;
		while(it2.hasNext()){
			Entry<String,String[]> entry=it2.next();
			String keyStr=entry.getKey();
			String values[]=entry.getValue();
			String key;
			String value="";
			if(keyStr.equals("user.id")||keyStr.equals("id")){
				continue;
			}
			if(keyStr.split("-")[1].equals("r")){ // 单选题目
				key=keyStr.split("-")[2];
				value=values[0];
				singleScore+=this.calScore(key, value, "1");
			}else{  // 多选
				key=keyStr.split("-")[2];
				for(String s:values){
					value+=s+",";
				}
				value=value.substring(0, value.length()-1);
				moreScore+=this.calScore(key, value, "2");
			}
		}
		totalScore=singleScore+moreScore;
		Score score = new Score();
		score.setSingleScore(singleScore);
		score.setMoreScore(moreScore);
		score.setScore(totalScore);
		score.setCreateDate(new Date());
		score.setPaperId(paper.getId());
		score.setUser(paper.getCurrentUser());
		scoreService.save(score);
		model.addAttribute("score", score.getScore());
		return "modules/gra/examResult";
	}
	
	private int calScore(String questionId,String userAnswer,String type)throws Exception{
		Question question=questionDao.get(questionId);
		if(userAnswer.equals(question.getAnswer())){
			if("1".equals(type)){
				return 20;
			}else{
				return 30;
			}
		}else{
			return 0;
		}
	}

}